# -*- coding: utf-8 -*-

#	This file is part of Kanji-Notification.

#	Kanji-Notification is free software: you can redistribute it 
#	and/or modify it under the terms of the GNU General Public License 
#	as published by the Free Software Foundation, either version 3 of 
#	the License, or	(at your option) any later version.
#
#	Kanji-Notification is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#
#	You should have received a copy of the GNU General Public License
#	along with Kanji-Notification. If not, see <http://www.gnu.org/licenses/>.

import os
import random
import wx
import wx.lib.agw.toasterbox as TB
from kn_parser import parse_xml
"""
This is the widget that will appear in the user's systray
"""
class KNTaskBarIcon(wx.TaskBarIcon):
    def __init__(self, frame):
        wx.TaskBarIcon.__init__(self)
        self.frame = frame
        self.SetIcon(wx.Icon('hi.png', wx.BITMAP_TYPE_PNG), 'Kanji-Notification')
        self.Bind(wx.EVT_MENU, self.OnTaskBarClose,  id=1)
        self.Bind(wx.EVT_MENU, self.OnFontSelection, id=2)
        self.Bind(wx.EVT_MENU, self.OnFileSelection, id=3)
        self.Bind(wx.EVT_MENU, self.OnSleepTime,     id=4)
        self.Bind(wx.EVT_MENU, self.OnAbout,         id=5)
        self.Bind(wx.EVT_MENU, self.OnDisplayTime,   id=6)
        
    def CreatePopupMenu(self):
        menu = wx.Menu()
        menu.Append(6, 'Display Time')
        menu.Append(4, 'Sleep Time')
        menu.Append(3, 'File Selection')
        menu.Append(2, 'Font Selection')
        menu.Append(1, 'Close')
        menu.AppendSeparator()
        menu.Append(5, 'About')   
        return menu
    def OnTaskBarClose(self, event):
        self.frame.Close()
    def OnFontSelection(self, event):
        data = wx.FontData()
        data.SetInitialFont(self.frame.kanji_font)
        dialog = wx.FontDialog(self.frame,data)
        if (dialog.ShowModal() == wx.ID_OK):
            self.frame.kanji_font = dialog.GetFontData().GetChosenFont()
        dialog.Destroy()
    def OnFileSelection(self, event):
        dialog = wx.FileDialog(self.frame,style = wx.FD_OPEN)
        if dialog.ShowModal() == wx.ID_OK:
            self.frame.file_name = dialog.GetPath()
            self.frame.root = parse_xml(self.frame.file_name)
            self.frame.sleep_time = self.frame.root.sleep
            self.frame.modification_time  = os.path.getmtime(self.frame.file_name)         
        dialog.Destroy()
    def OnSleepTime(self, event):
        dialog = wx.NumberEntryDialog(self.frame, "Sleep Time","Seconds","Sleep Time",self.frame.sleep_time,1,100000)
        if dialog.ShowModal() == wx.ID_OK:
            self.frame.sleep_time = dialog.GetValue()
            self.frame.timer.Stop()
            #Should we use self.frame.sleep_time or (self.frame.sleep_time + self.frame.display_time)?
            self.frame.timer.Start(self.frame.sleep_time*1000)
        dialog.Destroy()
    def OnDisplayTime(self, event):
        dialog = wx.NumberEntryDialog(self.frame, "Display Time","Seconds","Display Time",self.frame.display_time,1,100000)
        if dialog.ShowModal() == wx.ID_OK:
            self.frame.display_time = dialog.GetValue()
        dialog.Destroy()
    def OnAbout(self, event):
        data = wx.AboutDialogInfo()
        data.AddDeveloper("Bruno F. Lourenço")
        data.SetName("Kanji-Notification")
        data.SetVersion("0.1.2")
        data.SetWebSite("http://code.google.com/p/kanji-notification/")
        wx.AboutBox(data)
class DummyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)
        icon = wx.EmptyIcon()
        icon.CopyFromBitmap(wx.Bitmap("hi.png"))
        self.SetIcon(icon)
        #Create a new Timer with id 100. 100 is an arbitrary value
        self.TIMER_ID = 100
        self.timer = wx.Timer(self, self.TIMER_ID)
        #Bind the timer event
        
        self.taskbar = KNTaskBarIcon(self)
        #Get the display size so we can draw our popup messages
        #in the right place
        self.display_size = wx.GetDisplaySize()       

        wx.EVT_TIMER(self, self.TIMER_ID, self.OnTimer)
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.timer.Start(1000)

        #Default font
        self.kanji_font = wx.Font(40,wx.FONTFAMILY_DEFAULT,wx.FONTSTYLE_NORMAL,wx.FONTWEIGHT_NORMAL, faceName = "MS PMincho")

        try:
            f = open("kanji.xml")
            f.close()
            self.file_name = "kanji.xml"
            self.root = parse_xml(self.file_name)
            self.sleep_time = self.root.sleep
            self.modification_time  = os.path.getmtime(self.file_name)
        except IOError:
            self.file_name = None
        #Default display time. This value is arbitrary.
        self.display_time = 13
        
        
    def OnPaint(self, event):
        dc = wx.BufferedPaintDC( self.popup_panel )
        dc.GradientFillLinear( self.popup_panel.GetClientRect(),
                               wx.Colour(12,13,13), wx.Colour(153,160,163),
                               wx.SOUTH )
    def OnClose(self, event):
        self.timer.Stop()
        self.taskbar.Destroy()
        self.Destroy()
        
    def OnTimer(self,event):
        if (self.file_name is None):
            self.timer.Start(1000)
            return

        #If the file was modified, we parse it again
        aux = os.path.getmtime(self.file_name)
        if (aux > self.modification_time):
            self.modification_time = aux
            self.root = parse_xml(self.file_name)
            self.sleep_time = self.root.sleep

        #Get a random kanji
        kanji = random.choice(self.root.kanji)
        msg = "Kun: " + " , ".join(kanji.kun) + "\n"
        msg += "On: " + " , ".join(kanji.on) + "\n"
        msg += "Examples:\n"
        msg += "\n".join([aux.__unicode__() for aux in kanji.examples])
        ex_num = len(kanji.examples)

        #Calculate the  popup height. Each example is written with a
        #10 point typeface but we use 11 here to gain more space
        y = 90 + 11*(ex_num+1)
        self.popup = TB.ToasterBox(self.taskbar.frame, TB.TB_COMPLEX, closingstyle = TB.TB_ONCLICK )
        #350 is arbitrary, we might change it later if needed or maybe
        #change it to a user defined value
        self.popup.SetPopupSize((350,y))
        
        tbpanel = self.popup.GetToasterBoxWindow()
        self.popup_panel = wx.Panel(tbpanel, -1, style = (wx.DOUBLE_BORDER) )
        self.popup_panel.Bind( wx.EVT_PAINT, self.OnPaint )

        box = wx.BoxSizer(wx.HORIZONTAL)
        self.popup_panel.SetSizer(box)

        #This is where the kanji goes
        text = wx.StaticText(self.popup_panel, -1, kanji.uchar, style=wx.DOUBLE_BORDER | wx.ALIGN_CENTRE)
        text.SetFont(self.kanji_font)
        text.SetBackgroundColour('WHITE')
        box.Add(text,1,wx.ALL,4)

        #This is where the readings and the examples go
        text2 = wx.StaticText(self.popup_panel, -1,msg,style=wx.DOUBLE_BORDER)
        text2.SetFont(wx.Font(10,wx.DEFAULT,wx.NORMAL,wx.LIGHT))
        text2.SetBackgroundColour('WHITE')
        box.Add(text2,4,wx.ALL | wx.EXPAND,4)
        box.Layout()
        
        self.popup.AddPanel(self.popup_panel)
        self.popup.SetPopupPosition((self.display_size[0] - 350,self.display_size[1] - (y+50)))
        self.popup.SetPopupPauseTime(self.display_time*1000)
        #Show the popup
        self.popup.Play()
        #Start the timer again
        self.timer.Start((self.sleep_time+self.display_time)*1000)
        
class KNApp(wx.App):
    def OnInit(self):
        frame = DummyFrame(None, -1, 'Kanji-Notification')
        frame.Show(False)
        self.SetTopWindow(frame)
        return True

wx.SetDefaultPyEncoding("utf-8")
app = KNApp(0)
app.MainLoop()
